package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.bean.OrderSetting;
import com.atguigu.dao.OrderSettingMapper;
import com.atguigu.service.OrderSettingService;
import com.atguigu.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingMapper orderSettingMapper;


    @Override
    public void add(List<OrderSetting> orderSettingList) {
        //迭代集合中的数据
        for (OrderSetting orderSetting : orderSettingList) {
            //判断当前日期是否已经设置过预约日期
            long count = orderSettingMapper.findCountByOrderDate(orderSetting.getOrderDate());
            //如果设置过预约日期，更新number数量
            if (count > 0){
                orderSettingMapper.update(orderSetting);
            }else {
                orderSettingMapper.add(orderSetting);
            }
        }
    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {
        //获取当前月的第一天
        String dateBegin = date + "-1";
        //获取当前月的最后一天
        String dateEnd = DateUtils.getLastDayOfMonth(date);
        //将当前月的第一天和最后一天加入到map集合中
        Map<String,Object> map = new HashMap<>();
        map.put("dateBegin",dateBegin);
        map.put("dateEnd",dateEnd);
        //通过当月的第一天和最后一天获取到当月的所有日期的信息
        List<OrderSetting> list = orderSettingMapper.getLastDayOfMonth(map);
        //将数据封装到list<map>中返回
        List<Map> dateList = new ArrayList<>();
        for (OrderSetting orderSetting : list) {
            //将数据格式转换成和前端一致
            Map orderSettingMap = new HashMap();
            orderSettingMap.put("date",orderSetting.getOrderDate().getDate());
            orderSettingMap.put("number",orderSetting.getNumber());
            Integer reservations = orderSetting.getReservations();
            if (reservations == null) {
                reservations = 0;
            }
            orderSettingMap.put("reservations",reservations);
            dateList.add(orderSettingMap);
        }
        return dateList;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        long count = orderSettingMapper.findCountByOrderDate(orderSetting.getOrderDate());
        //如果设置过预约日期，更新number数量
        if (count > 0){
            orderSettingMapper.update(orderSetting);
        }else {
            orderSettingMapper.add(orderSetting);
        }
    }
}
